#!/usr/bin/perl -w
package node::swap_space;

use Config;

sub new {
my $proto = shift;
my $class = ref($proto) || $proto;
my $self  = {};
my $name=shift;

	if($Config{osname} ne "hpux" && $Config{osname} ne "linux") {
		::warnmsg("Currently only works on HP-UX/Linux!") if defined(&::warnmsg);
		return undef;
	}
	$self->{name}=$name;
	$self->{min_interval}=30;
	$self->{description}="Swap space monitor";
	bless ($self, $class);
	return($self);
}

sub action_args {
my $self=shift;

	return "threshold";

}

sub min_interval {
my $self=shift;

	return $self->{min_interval};
}

#################################################################
# Since action_args is "threshold" we return a % value - i.e.	#
# a number between 0 and 100 inclusive.				#
#################################################################

sub test {
my $self=shift;

	if($Config{osname} eq "linux") {
		if(! -f "/proc/meminfo") {
			::warnmsg("The '/proc/meminfo' file can not be found.");
			return(0);
		}
		my ($cline,$fd);
		if(!open($fd,"/proc/meminfo")) {
			::warnmsg("The '/proc/meminfo' file can not be opened.");
			return(0);
		}
		my ($total,$free)=(-1,-1);
		while($cline=<$fd>) {
			chomp $cline;
			my @F=split(/\s+/,$cline);
			if($F[0] eq "SwapTotal:") {
				$total=int($F[1]);
			}
			if($F[0] eq "SwapFree:") {
				$free=int($F[1]);
			}
		}
		close($fd);
		if($total==-1 || $free==-1) {
			::warnmsg("No swap information found in '/proc/meminfo'.");
			return(0);
		}
		#########################################################
		# We have swap information, so turn it into a % used	#
		# of swap space.					#
		#########################################################
		my $used=$total=$free;
		my $perc=int($used/$total*100);
		return $perc;
	}
	my ($d,$fd);
	if(!open($fd,"/usr/sbin/swapinfo -tam|")) {
		::warnmsg("Unable to run the 'swapinfo' command.") if defined(&::warnmsg);
		return(0);
	}
	while(<$fd>) {
		chomp;
		my  @F=split;
		next if $F[0] ne "total";
		$d=$F[4];
		$d=~ s/\%//;
	}
	close($fd);
	return int($d);
}

sub reset {
my $self=shift;

}

sub desc {
my $self=shift;

	return $self->{description};
}

1;

